import React, { useEffect, useTransition,useState  } from 'react'
import {Button, Card,Modal,Form,type FormProps, Input,message,Select,Radio,TreeSelect   } from 'antd'
import { ExclamationCircleOutlined  } from '@ant-design/icons'; 
import { useNavigate } from 'react-router-dom';
import { ProFormColumnsType } from '@ant-design/pro-components'
import { listDept, getDept, delDept, addDept, updateDept, listDeptExcludeChild } from "@/api/system/dept";
import useCacheAlive from '@/hooks/useCacheAlive'
import MemoTable from '@/components/MemoTable';
import { useTranslation } from 'react-i18next';
import { handleTree } from '@/utils/helper';
import md5 from "js-md5"


const { TreeNode } = TreeSelect; 
type FieldType = {
    username?: string;
    password?: string;
    phonenumber?:string;
    userId?:number;
    roleId?:number;
  };

const Dept = () => {
  const navigate = useNavigate();
  const { t } = useTranslation()
  const [modalVisible, setModalVisible] = useState(false);  
  const [userTitle,setUserTitle] = useState("")
  const [deptOptions,setDeptOptions] = useState([])
  const [selectedValue, setSelectedValue] = useState(null); // 保存选中的值（id）  
  const [selectedName, setSelectedName] = useState(''); // 保存选中的名称  
  const [form] = Form.useForm();  
  const [onReloadNum,setOnReloadNum] = useState(null)

  const handleTreeSelectChange = (value, label) => {  
    setSelectedValue(value); // 保存选中的id  
    setSelectedName(label); // 保存选中的名称  
    console.log('Selected ID:', value);  
    console.log('Selected Name:', label);  
  }; 

  const formColumns:ProFormColumnsType[] = [{
    title: '部门名称',
    dataIndex: 'deptName',
    valueType: 'text', 
  }]


  const columns: any = [
    {
      title: '部门名称',
      dataIndex: 'deptName',
      key: 'deptName',
      width:100,
      fixed:'left',
    },
    {
      title:'排序',
      dataIndex: 'orderNum',
      key: 'orderNum',
      width:100,
      fixed:'left',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width:100,
      fixed:'left',
      render: (_, record) => {
        if(record.status == 0){
            return (<>
                <span>正常</span>
              </>)
        }else{
            return (<>
                <span>停用</span>
              </>)
        }
       
    }
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width:80,
      fixed:'left',
    },
    {
        title: t('action'),
        width: 120,
        fixed: 'right',
        render: (_, record) => {
            const handleEdit = () => {  
                //进行弹窗
                setUserTitle('修改部门')
                // const userId = record.userId
                console.log(record,'record')
                form.setFieldsValue(record)
                listDeptExcludeChild(record.deptId).then(response => {
                    const list = handleTree(response.data.data, "deptId",'parentId','children');
                    setDeptOptions(list)
                    form.setFieldsValue(record)
                    setModalVisible(true);  
                })
            
              }; 
              const handleAddByRow = ()=>{
                  //进行弹窗
                  setUserTitle('新增部门')
                  // const userId = record.userId
                  console.log(record,'record')
                  form.setFieldsValue(record)
                  listDeptExcludeChild(record.deptId).then(response => {
                    const list = handleTree(response.data.data, "deptId",'parentId','children');
                    setDeptOptions(list)
                    form.setFieldsValue(record)
                    setModalVisible(true);  
                })
              }
              const showDeleteConfirm = () => {  
                Modal.confirm({  
                  title: 'Confirm Delete部门吗?',  
                  icon: <ExclamationCircleOutlined />,  
                  okText: '确认',  
                  cancelText: '取消',  
                  onOk() {  
                    console.log(record,'record')
                    handleDelete(record.deptId);  
                  },  
                  onCancel() {  
                    console.log('Cancel');  
                  },  
                });  
              };  
            if(record.deptId == 100){
                return (<>
                    <Button type='link' onClick={handleEdit}>修改</Button>
                    <Button type='link' onClick={handleAddByRow}>新增</Button>
                  </>)
            }else{
              return (<>
                <Button type='link' onClick={handleEdit}>修改</Button>
                <Button type='link' onClick={handleAddByRow}>新增</Button>
                <Button type='link' onClick={showDeleteConfirm}>删除</Button>
              </>)
            }
          
        }
      }
  ];

  const handleDelete = (deptId) => {
    const id = deptId
    console.log(deptId,'record')
    delDept(id).then(res=>{
        if(res.data.code ==200){
            // 假设你已经处理完数据，关闭弹窗  
            message.success('部门删除成功'); 
            setOnReloadNum(Date.now())
        }else{
            message.error('部门删除失败：' + res.data.msg); 
        }
    })
}

  const handleAdd = () =>{
    form.resetFields()
    setUserTitle('新增部门')
    listDept().then(response => {
        const list = handleTree(response.data.data, "deptId",'parentId','children');
        setDeptOptions(list)
        console.log(list,'list')
        setModalVisible(true)
      });
    
  }

  const renderOperator = <>
    <Button type="primary" size="small" onClick={handleAdd}>{t('add')}</Button>
  </>


  const getData = async (formData) => {
    const { success, data} = await listDept({...formData, })
    if(!success) return false
 
    const list = handleTree(data.data,'deptId','parentId','children')
    console.log(list)
    return {
      data: list,
      total: data.total
    }
  } 

  const handleModalCancel = () => {  
    form.resetFields(); // 重置表单字段  
    setModalVisible(false);  
  };   


  const handleFormFinish = (values) => {  
    // 处理表单提交逻辑，比如发送API请求  
    console.log('Form values:', values);
    if(userTitle=='新增部门'){
        values.deptId = null
        addDept(values).then(res=>{
            console.log(res,'res')
            if(res.data.code ==200){
                // 假设你已经处理完数据，关闭弹窗  
                message.success('部门添加成功');
                handleModalCancel();  
                setOnReloadNum(Date.now())
            }else{
                message.error('部门添加失败：' + res.data.msg); 
            }
        })  
    }else{
        values.deptId = form.getFieldValue('deptId')
        updateDept(values).then(res=>{
            console.log(res,'res')
            if(res.data.code ==200){
                // 假设你已经处理完数据，关闭弹窗  
                message.success('部门更新成功');
                handleModalCancel();  
                setOnReloadNum(Date.now())
            }else{
                message.error('部门更新失败：' + res.data.msg); 
            }
        })  
    }
  
  };  
  // 根据 userTitle 的值来决定是否显示密码输入框  

  return (
    <>
    <MemoTable 
      name='basic'
      formColumns={formColumns}
      columns={columns as any}
      rowKey='deptId'
      operator={renderOperator}
      getData={getData}
      refreshKey={onReloadNum}
    />
     <Modal  
        title={userTitle}  
        open={modalVisible}  
        onCancel={handleModalCancel}  
        footer={[  
          <Button key="back" onClick={handleModalCancel}>  
            取消  
          </Button>,  
          <Button key="submit" type="primary" onClick={() => form.validateFields().then(handleFormFinish)}>  
            提交  
          </Button>,  
        ]}  
      >  
        <Form form={form} layout="vertical" onFinish={handleFormFinish}>  
          <Form.Item  
            name="parentId"  
            label="上级部门"  
            rules={[{ required: true, message: '请输入部门名!' }]}  
          >  
             <TreeSelect  
                style={{ width: '100%' }}  
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}  
                treeDefaultExpandAll  
                placeholder="Please select"  
                treeData={deptOptions}  
                value={selectedValue}  
                onChange={handleTreeSelectChange}  
                /> 
          </Form.Item>  
  
          <Form.Item  
            name="deptName"  
            label="部门名称"  
            rules={[{ required: true, message: '请输入昵称!' }]}  
          >  
            <Input />  
          </Form.Item>  
  
          <Form.Item  
            name="orderNum"  
            label="显示排序"  
            rules={[{ required: true, message: '请输入显示排序!' }]}  
          >  
            <Input />  
          </Form.Item>
          <Form.Item  
            name="leader"  
            label="负责人"  
            // rules={[{ required: true, message: '请输入密码!' }]}  
          >  
            <Input />  
          </Form.Item>  
          <Form.Item  
            name="phone"  
            label="联系电话"  
            // rules={[{ required: true, message: '请输入密码!' }]}  
          >  
            <Input />  
          </Form.Item>  
          <Form.Item  
            name="email"  
            label="邮箱"  
            // rules={[{ required: true, message: '请输入密码!' }]}  
          >  
            <Input />  
          </Form.Item> 
          <Form.Item  
            name="status"  
            label="部门状态"  
            // rules={[{ required: true, message: '请输入密码!' }]}  
          >  
            <Radio.Group>  
                <Radio value={'0'}>正常</Radio>  
                <Radio value={'1'}>停用</Radio>  
            </Radio.Group> 
          </Form.Item> 
        </Form>  
      </Modal>   
    </>
  )
}
export default Dept
